package com.ssyc.main.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.ssyc.common.appupdate.AppUpdateUtil;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.utils.AESOperator;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.cleanedittext.CommonEditText;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.main.R;
import com.ssyc.main.bean.LoginInfo;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


/**
 * 登录界面
 * Created by Administrator on 2018/1/11 0011.
 */

public class LoginActivity extends Activity implements View.OnClickListener {

    //是否记住账号的标记
    private boolean isRememberCount;
    //账号
    private CommonEditText mEtTel;
    //密码
    private CommonEditText mEtPwd;
    //记住账号和密码
    private ImageView mLvJzzh;
    private LinearLayout mLlJzmm;
    //忘记密码
    private TextView mTvForgetPwd;
    //登录
    private Button mBtLogin;

    //创建账号的相对布局和按钮
    private LinearLayout llCreateAccount;
    private Button btCreateAccount;
    private LinearLayout llMain;

    //账号的线性布局
    private LinearLayout llAcount;

    //密码的线性布局
    private LinearLayout llPwd;

    private ImageView lvAccount;
    private ImageView lvPwd;

    //角色
    private int role;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity_login);

        //初始化视图
        initView();

        //设置监听
        initListener();

        //做适配处理
        doAdaptiveAction();

        //初始化状态值
        syncState();

        //检查更新
        AppUpdateUtil.updateVersion(this);
    }


    /**
     * 初始化视图的方法
     */
    private void initView() {
        mEtTel = findViewById(R.id.et_tel);
        mEtPwd = findViewById(R.id.et_pwd);
        lvAccount = findViewById(R.id.lv_account);
        lvPwd = findViewById(R.id.lv_pwd);
        mLvJzzh = findViewById(R.id.lv_jzzh);
        mLlJzmm = findViewById(R.id.ll_jzmm);
        mLlJzmm.setOnClickListener(this);
        mTvForgetPwd = findViewById(R.id.tv_forget_pwd);
        mTvForgetPwd.setOnClickListener(this);
        mBtLogin = findViewById(R.id.bt_login);
        mBtLogin.setEnabled(false);
        mBtLogin.setOnClickListener(this);
        llCreateAccount = findViewById(R.id.ll_create_account);
        btCreateAccount = findViewById(R.id.bt_create_account);
        btCreateAccount.setOnClickListener(this);
        llMain = findViewById(R.id.ll_main);
        llAcount = findViewById(R.id.ll_account);
        llPwd = findViewById(R.id.ll_pwd);

        //如果是校长和老师不显示创建账号,2是老师,3是校长
        if (2 == SPUtil.getInt(this, SpKeys.ROLETYPE) || 3 == SPUtil.getInt(this, SpKeys.ROLETYPE)) {
            llCreateAccount.setVisibility(View.GONE);
        } else {
            llCreateAccount.setVisibility(View.VISIBLE);
        }

        mEtTel.getEdittext().setInputType(InputType.TYPE_CLASS_PHONE);


//        mEtPwd.getEdittext().setInputType(InputType.);
    }

    /**
     * 设置监听
     */
    private void initListener() {
        mEtTel.setListener(new CommonEditText.onAfterInputListener() {
            @Override
            public void after() {
                synvLoginState();
            }
        });
        mEtPwd.setListener(new CommonEditText.onAfterInputListener() {
            @Override
            public void after() {
                synvLoginState();
            }
        });
    }

    /**
     * 同步登录按钮的方法
     */
    private void synvLoginState() {
        String tel = mEtTel.getEdittext().getText().toString().trim();
        String pwd = mEtPwd.getEdittext().getText().toString().trim();
        if (TextUtils.isEmpty(tel) || TextUtils.isEmpty(pwd)) {
            mBtLogin.setBackgroundResource(R.drawable.main_login_bg_unselect);
            mBtLogin.setEnabled(false);
        } else {
            mBtLogin.setBackgroundResource(R.drawable.main_login_bg);
            mBtLogin.setEnabled(true);
        }
    }

    /**
     * 对布局做动态的适配处理
     * 1:1.138:0.536比例值
     */
    private void doAdaptiveAction() {
        //获取屏幕高度
        int screenHeight = ScreenUtils.getScreenHeight(this);
        //获取屏幕宽度
        int screenWidth = ScreenUtils.getScreenWidth(this);
        //获取账号和密码以及登录按钮整体布局的高度
        int centerHeight = screenHeight * 1138 / (1000 + 1138 + 536);
        int centerWidth = screenWidth * 509 / 756;
        //取账号和密码布局的高度为整体高度的2/7
        int itemHeight = centerHeight * 2 / 7;
        LinearLayout.LayoutParams lpCenter = new LinearLayout.LayoutParams(centerWidth, itemHeight);
        lpCenter.gravity = Gravity.CENTER_HORIZONTAL;
        llAcount.setLayoutParams(lpCenter);
        llPwd.setLayoutParams(lpCenter);

        //动态确定账号和密码图片以及输入框的位置
        LinearLayout.LayoutParams lpLv = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpLv.gravity = Gravity.BOTTOM;

        //计算底边距
        lpLv.bottomMargin = itemHeight * 2 / 7;
        lvAccount.setLayoutParams(lpLv);
        lvPwd.setLayoutParams(lpLv);

        LinearLayout.LayoutParams lpEt = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lpEt.bottomMargin = itemHeight * 8 / 76;
        lpEt.topMargin = itemHeight * 24 / 76;
        mEtTel.setLayoutParams(lpEt);
        mEtPwd.setLayoutParams(lpEt);

        //确定登录按钮的位置
        //计算按钮的宽高和底边距
        int loginBtWidth = centerWidth * 198 / 234;
        int loginBtHeight = itemHeight * 30 / 66;
        LinearLayout.LayoutParams lpLogin = new LinearLayout.LayoutParams(loginBtWidth, loginBtHeight);
        lpLogin.bottomMargin = itemHeight * 24 / 76;
        mBtLogin.setLayoutParams(lpLogin);

        //确定创建账号的位置,先计算整体底部的高度
        int bottomHeight = screenHeight * 536 / (1000 + 1138 + 536);
        //计算创建账号背景条的高度
        int createAccountBgHeight = bottomHeight * 58 / 130;
        RelativeLayout.LayoutParams lpCreateAccountBg = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, createAccountBgHeight);
        lpCreateAccountBg.topMargin = bottomHeight * 30 / 134;
        llCreateAccount.setLayoutParams(lpCreateAccountBg);

        //计算创建账号按钮的宽高
        int btCreateAccountWidth = screenWidth * 206 / 376;
        int btCreateAccountHeight = createAccountBgHeight * 26 / 40;
        LinearLayout.LayoutParams lpCreateAccountBt = new LinearLayout.LayoutParams(btCreateAccountWidth, btCreateAccountHeight);
        lpCreateAccountBt.gravity = Gravity.CENTER;
        btCreateAccount.setLayoutParams(lpCreateAccountBt);

    }


    /**
     * 初次进入同步状态的方法
     * 1.是否显示账号
     * 2.是否勾选记住账号
     */
    private void syncState() {

        //获取身份角色
        role = SPUtil.getInt(this, SpKeys.ROLETYPE);

        isRememberCount = SPUtil.getBoolean(this, SpKeys.ISRENMERCOUNT);
        if (isRememberCount) {
            //记住账号的操作
            mLvJzzh.setImageResource(R.drawable.checked);
            mEtTel.getEdittext().setText(SPUtil.getString(this, SpKeys.REMBERACCOUNT));
        } else {
            //不记住账号的操作
            mLvJzzh.setImageResource(R.drawable.unchecked);
            mEtTel.getEdittext().setText("");
            mEtPwd.getEdittext().setText("");
        }
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_jzmm) {
            //记住账号
            doRememberCount();
        } else if (id == R.id.tv_forget_pwd) {
            //忘记密码,跳转到忘记密码界面
            UiUtils.startActivity(this, ResetPasswordActivity.class);
        } else if (id == R.id.bt_login) {
            //登录
            doLoginAction();
        } else if (id == R.id.bt_create_account) {
            //创建账号,跳转到注册界面
            UiUtils.startActivity(this, RegisterActivity.class);
        }
    }

    /**
     * 点击记住账号的操作
     */
    private void doRememberCount() {
        //对状态取反
        isRememberCount = !isRememberCount;
        if (isRememberCount) {
            mLvJzzh.setImageResource(R.drawable.checked);
        } else {
            mLvJzzh.setImageResource(R.drawable.main_login_accout_normal);
        }
        SPUtil.put(this, SpKeys.ISRENMERCOUNT, isRememberCount);
    }

    /**
     * 点击登录后的操作
     */
    private void doLoginAction() {
        //获取手机号
        String tel = mEtTel.getEdittext().getText().toString().trim();

        //获取输入的密码
        String pwd = mEtPwd.getEdittext().getText().toString().trim();

        //判断非空处理
        if (TextUtils.isEmpty(tel)) {
            SnackbarUtil.ShortSnackbar(llMain, "手机号不能为空", 0).show();
            return;
        }


        //判断非空处理
        if (TextUtils.isEmpty(pwd)) {
            SnackbarUtil.ShortSnackbar(llMain, "密码不能为空", 0).show();
            return;
        }
        //请求登录接口
        loginHttp(tel, pwd);


    }

    /**
     * 请求登录接口
     */
    private void loginHttp(String tel, String pwd) {
        CustomDialogManager.show(this, "登录中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "2");

        //加密
        String acc = null;
        String pswd = null;
        String registration_id = null;
        try {
            acc = AESOperator.getInstance().encrypt(tel);
            pswd = AESOperator.getInstance().encrypt(pwd);
            registration_id = AESOperator.getInstance().encrypt(SPUtil.getString(this, SpKeys.JPUSH_ID));
        } catch (Exception e) {
            e.printStackTrace();
        }

        map.put("acc", acc.trim());
        map.put("role", role + "");
        map.put("psw", pswd.trim());
        map.put("registration_id", registration_id.trim());
        map.put("platform", "8");

        LogUtils.iTag("test",map.toString());
        LogUtils.iTag("test",HttpAdress.LOGIN);

        HttpUtils.post(HttpAdress.LOGIN, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                //请求失败
                CustomDialogManager.dissmiss();
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                //请求成功
                Log.i("test", response);

                //解析数据
                LoginInfo info = GsonUtil.jsonToBean(response, LoginInfo.class);
                CustomDialogManager.dissmiss();

                //判断返回状态码  101103为registration_id为空，但密码正确登录成功
                if ("200".equals(info.state) || "101103".equals(info.state)
                        || "101104".equals(info.state)) {

                    //登录成功
//                    UiUtils.Toast("登录成功", false);

                    //保存账号
                    SPUtil.put(LoginActivity.this, SpKeys.ACCOUNT, tel);

                    //记住账号
                    SPUtil.put(LoginActivity.this, SpKeys.REMBERACCOUNT, tel);

                    //保存姓名
                    SPUtil.put(LoginActivity.this, SpKeys.NAME, info.getData().get(0).getName());

                    //保存头像
                    SPUtil.put(LoginActivity.this, SpKeys.ICON, info.getData().get(0).getIcon());

                    //保存TOKEN1
                    SPUtil.put(LoginActivity.this, SpKeys.TOKEN1, info.getData().get(0).getToken1());

                    //保存TOKEN2
                    SPUtil.put(LoginActivity.this, SpKeys.TOKEN2, info.getData().get(0).getToken2());
                    //保存学校ID
                    SPUtil.put(LoginActivity.this, SpKeys.SCHOOLID, info.getData().get(0).getSchoolid());
                    //保存学校名称
                    SPUtil.put(LoginActivity.this, SpKeys.SCHOOLNAME, info.getData().get(0).getSchoolname());
                    //保存是否隐藏群组
                    SPUtil.put(LoginActivity.this, SpKeys.DISABLEGROUP, info.getData().get(0).getDisablegroup());

                    //使用专场动画根据角色类型跳转到不同的界面,注意:学生端还需要判断是否是第一次进入APP
                    int type = SPUtil.getInt(LoginActivity.this, SpKeys.ROLETYPE);

                    //学生端
                    if (type == 0) {

                        if ("1".equals(info.getData().get(0).getHaspet())) {
                            //已拥有宠物
                            //保存宠物昵称
                            SPUtil.put(LoginActivity.this, SpKeys.PETNAME, info.getData().get(0).getPetname());
                            //保存宠物类型
                            SPUtil.put(LoginActivity.this, SpKeys.SERVICEPETTYPE, info.getData().get(0).getPettype());

                            SPUtil.put(LoginActivity.this, SpKeys.PETGENDAR, info.getData().get(0).getPetsex());

                            ARouter.getInstance().build("/student/StudentMainActivity")
                                    .withTransition(R.anim.translate_right_to_center, R.anim.translate_center_to_left).navigation();

                        } else if ("0".equals(info.getData().get(0).getHaspet())) {
                            //未拥有宠物
                            ARouter.getInstance().build("/student/studentgetpetone")
                                    .withTransition(R.anim.translate_right_to_center, R.anim.translate_center_to_left).navigation();
                        }
                    }

                    //家长端
                    if (type == 1) {
                        ARouter.getInstance().build("/parents/ParentsMainActivity").navigation();
                    }

                    //教师端
                    if (type == 2) {
                        //保存USERTYPE
                        SPUtil.put(LoginActivity.this, SpKeys.USERTYPE, "1");
                        ARouter.getInstance().build("/teacher/TeacherMainActivity").navigation();
                    }

                    //校长端
                    if (type == 3) {
                        ARouter.getInstance().build("/master/MasterMainActivity").navigation();
                    }

                    //登录云信服务器
//                    LoginImAccount();

                    finish();

                } else if ("-1".equals(info.state)) {
                    CustomDialogManager.dissmiss();
                    UiUtils.Toast("服务器异常，请稍后重试", false);

                } else if ("101101".equals(info.state)) {
                    CustomDialogManager.dissmiss();
                    UiUtils.Toast("号码尚未注册，请核对账号", false);

                } else if ("101102".equals(info.state)) {
                    CustomDialogManager.dissmiss();
                    UiUtils.Toast("密码不正确，请核对密码", false);

                } else {
                    CustomDialogManager.dissmiss();
                    UiUtils.Toast("登录失败，错误码" + info.state, false);
                }
            }
        });


    }

    /**
     * 登录云信服务器
     */
//    private void LoginImAccount() {
//
//        //云信的账号由APP的账号+用户角色组成
//        String account = SPUtil.getString(this, SpKeys.ACCOUNT) + SPUtil.getInt(this, SpKeys.ROLETYPE);
//
//        String token = SPUtil.getString(this, SpKeys.TOKEN2);
//
//        com.netease.nimlib.sdk.auth.LoginInfo info = new com.netease.nimlib.sdk.auth.LoginInfo(account, token);
//
//        NimUIKit.login(info, new RequestCallback<com.netease.nimlib.sdk.auth.LoginInfo>() {
//            @Override
//            public void onSuccess(com.netease.nimlib.sdk.auth.LoginInfo loginInfo) {
//                Log.i("test", "登录成功,账号信息是:" + loginInfo.getAccount());
//            }
//
//            @Override
//            public void onFailed(int code) {
//                Log.i("test", "登录失败,失败信息是:" + code);
//            }
//
//            @Override
//            public void onException(Throwable throwable) {
//
//            }
//        });
//    }

    /**
     * 实现全局的事件分发,点击非输入框位置隐藏软键盘
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    /**
     * 是否隐藏软键盘
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();

//            if (event.getX() > left && event.getX() < right
//                    && event.getY() > top && event.getY() < bottom) {
//                // 点击的是输入框区域，保留点击EditText的事件
//                return false;
//            } else {
//                return true;
//            }

            if (event.getX() > 0 && event.getX() < ScreenUtils.getScreenWidth(this)
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


}
